﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DataAccessLayer;

namespace QuestionManager
{
    public enum ACTION_STATE
    {
        Insert, Update
    }

    public partial class QuestionManager : Form
    {
        public string USER_ID = "user_id";
        private ACTION_STATE _currentState = ACTION_STATE.Insert;
        public ACTION_STATE CurrentState
        {
            get { return _currentState; }
            set { _currentState = value; }
        }

        const int RADIO_CHECK_CORRECT = 1;
        const int RICHTEXTBOX_ANSWER_CONTENT = 2;
        const int PICTUREBOX_IMAGE = 3;

        private Dictionary<string, object> DataQuestionToUpDate = new Dictionary<string, object>();
        private List<Diffculty> Diffculties;
        private List<Course> Courses;
        private List<Time> Times;
        private List<Professor> Professors;

        private Dictionary<int, Control>[] AnswerItemArray = new Dictionary<int, Control>[5];
        private DataTable table = null;
        public QuestionManager()
        {
            InitializeComponent();

            this.InitUI();
        }

        public void SetState(ACTION_STATE state)
        {
            btnCreateQuestion.Click -= new EventHandler(btnCreateQuestion_Click);
            btnCreateQuestion.Click -= new EventHandler(btnUpdateQuestion_Click);
            
            if (state == ACTION_STATE.Insert)
            {
                btnCancelUpdate.Visible = false;
                btnCreateQuestion.Click += new EventHandler(btnCreateQuestion_Click);
                btnCreateQuestion.Text = "Create Question";
            }
            else if (state == ACTION_STATE.Update)
            {
                btnCancelUpdate.Visible = true;
                btnCreateQuestion.Click += new EventHandler(btnUpdateQuestion_Click);
                btnCreateQuestion.Text = "Update Question";
            }
        }

        //Summary
        // create LinkedList of GUI Components
        // add event
        //------------------------------
        private void InitUI()
        {
            int index = 0;

            //create answer first
            Dictionary<int, Control> first = new Dictionary<int, Control>();
            bnCorrectAnswer_1.Checked = true;
            first.Add(RADIO_CHECK_CORRECT, bnCorrectAnswer_1);
            first.Add(RICHTEXTBOX_ANSWER_CONTENT, rtbAnswerContent_1);
            first.Add(PICTUREBOX_IMAGE, pbImageAnswer_1);
            AnswerItemArray[index++] = first;

            //create answer secound
            Dictionary<int, Control> secound = new Dictionary<int, Control>();
            secound.Add(RADIO_CHECK_CORRECT, bnCorrectAnswer_2);
            secound.Add(RICHTEXTBOX_ANSWER_CONTENT, rtbAnswerContent_2);
            secound.Add(PICTUREBOX_IMAGE, pbImageAnswer_2);
            AnswerItemArray[index++] = secound;

            //create answer thrid
            Dictionary<int, Control> thrid = new Dictionary<int, Control>();
            thrid.Add(RADIO_CHECK_CORRECT, bnCorrectAnswer_3);
            thrid.Add(RICHTEXTBOX_ANSWER_CONTENT, rtbAnswerContent_3);
            thrid.Add(PICTUREBOX_IMAGE, pbImageAnswer_3);
            AnswerItemArray[index++] = thrid;

            //create answer fourth
            Dictionary<int, Control> fourth = new Dictionary<int, Control>();
            fourth.Add(RADIO_CHECK_CORRECT, bnCorrectAnswer_4);
            fourth.Add(RICHTEXTBOX_ANSWER_CONTENT, rtbAnswerContent_4);
            fourth.Add(PICTUREBOX_IMAGE, pbImageAnswer_4);
            AnswerItemArray[index++] = fourth;

            //create answer fifth
            Dictionary<int, Control> fifth = new Dictionary<int, Control>();
            fifth.Add(RADIO_CHECK_CORRECT, bnCorrectAnswer_5);
            fifth.Add(RICHTEXTBOX_ANSWER_CONTENT, rtbAnswerContent_5);
            fifth.Add(PICTUREBOX_IMAGE, pbImageAnswer_5);
            AnswerItemArray[index++] = fifth;

            pbImageAnswer_1.Click += new EventHandler(pbImageAnswer_Click);
            pbImageAnswer_2.Click += new EventHandler(pbImageAnswer_Click);
            pbImageAnswer_3.Click += new EventHandler(pbImageAnswer_Click);
            pbImageAnswer_4.Click += new EventHandler(pbImageAnswer_Click);
            pbImageAnswer_5.Click += new EventHandler(pbImageAnswer_Click);
            pbImageQuestion.Click += new EventHandler(pbImageAnswer_Click);

            //Diffculty
            Diffculties = GetBussiness.getInstace().GetDiffculty();
            if (Diffculties != null)
            {
                foreach (Diffculty item in Diffculties)
                {
                    cbDiffculty.Items.Add(item.Name);
                }
                if (cbDiffculty.Items.Count > 0) cbDiffculty.SelectedIndex = 0;
            }

            Courses = GetBussiness.getInstace().GetCourse();
            if (Courses != null)
            {
                foreach (Course item in Courses)
                {
                    cbCourse.Items.Add(item.Name);
                }
                if (cbCourse.Items.Count > 0) cbCourse.SelectedIndex = 0;
            }

            Times = GetBussiness.getInstace().GetTime();
            if (Times != null)
            {
                foreach (Time item in Times)
                {
                    cbTime.Items.Add(item.Value);
                }
                if (cbTime.Items.Count > 0) cbTime.SelectedIndex = 0;
            }

            Professors = GetBussiness.getInstace().GetProfessor();
            if (Professors != null)
            {
                foreach (Professor item in Professors)
                {
                    cbProfessor.Items.Add(item.Name);
                }
                if (cbProfessor.Items.Count > 0) cbProfessor.SelectedIndex = 0;
            }
            SetState(ACTION_STATE.Insert);

            //load question
            LoadQuestionListData();
        }

        void LoadQuestionListData()
        {
            table = DAO_Question.LoadAll();
            if (table != null)
            {
                dataGridViewQuestion.DataSource = table;
                dataGridViewQuestion.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }
        }

        void pbImageAnswer_Click(object sender, EventArgs e)
        {
            if (sender != null && sender is PictureBox)
            {
                PictureBox temp = sender as PictureBox;
                var fd = new OpenFileDialog();
                fd.Filter = "Jpg (*.Jpg)|*.jpg;| Bmp (*.BMP)|*.BMP;| Png (*.Png)|*.Png";
                fd.AddExtension = true;
                if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Image img = new Bitmap(fd.FileName);
                    temp.Image = img;

                    string subPath = "img\\";
                    bool isExists = System.IO.Directory.Exists(subPath);

                    if (!isExists) System.IO.Directory.CreateDirectory(subPath);
                    string savedTo = subPath + fd.SafeFileName;

                    switch (Path.GetExtension(savedTo).ToUpper())
                    {
                        case ".BMP":
                            img.Save(savedTo, System.Drawing.Imaging.ImageFormat.Bmp);
                            break;
                        case ".JPG":
                            img.Save(savedTo, System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        case ".PNG":
                            img.Save(savedTo, System.Drawing.Imaging.ImageFormat.Png);
                            break;
                        default:
                            break;
                    }
                    temp.Tag = savedTo;

                    fd.RestoreDirectory = true;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnUpdateQuestion_Click(object sender, EventArgs e)
        {
            Diffculty _diffculty = Diffculties[cbDiffculty.SelectedIndex];
            Course _course = Courses[cbCourse.SelectedIndex];
            Time _time = Times[cbTime.SelectedIndex];
            Professor _professor = Professors[cbProfessor.SelectedIndex];
            string _imagePath = pbImageQuestion.Tag != null ? pbImageQuestion.Tag.ToString() : "";
            string _questionContent = rtbQuestionContent.Text;
            if (String.IsNullOrEmpty(_questionContent))
            {
                this.ErrorNotify("Please enter your question.");
                return;
            }
            USER_ID = _professor.ID;

            QuestionItem questionItem = new QuestionItem();
            questionItem.Diffculty = _diffculty;
            questionItem.Course = _course;
            questionItem.Time = _time;
            questionItem.Professor = _professor;
            questionItem.ImagePath = _imagePath;
            questionItem.QuestionContent = _questionContent;

            List<AnswerItem> AnswerItems = new List<AnswerItem>();

            foreach (Dictionary<int, Control> answerPanel in AnswerItemArray)
            {
                if (answerPanel != null && answerPanel.ContainsKey(RADIO_CHECK_CORRECT)
                                        && answerPanel.ContainsKey(RICHTEXTBOX_ANSWER_CONTENT)
                                        && answerPanel.ContainsKey(PICTUREBOX_IMAGE))
                {
                    RadioButton cbCorrect = answerPanel[RADIO_CHECK_CORRECT] as RadioButton;
                    RichTextBox rtbAnswerContent = answerPanel[RICHTEXTBOX_ANSWER_CONTENT] as RichTextBox;
                    PictureBox pbImageAnswer = answerPanel[PICTUREBOX_IMAGE] as PictureBox;

                    if (cbCorrect != null && rtbAnswerContent != null && pbImageAnswer != null)
                    {
                        AnswerItem item = new AnswerItem();
                        string _answerContent = rtbAnswerContent.Text.Trim();
                        if (String.IsNullOrEmpty(_answerContent))
                        {
                            //ignore empty question
                            continue;
                        }
                        item.TextContent = _answerContent;
                        item.Correct = cbCorrect.Checked;
                        item.ImagePath = pbImageAnswer.Tag != null ? pbImageAnswer.Tag.ToString() : "";

                        AnswerItems.Add(item);
                    }
                }
            }

            if (AnswerItems.Count > 0)
            {
                if (PushBussiness.getInstace().UpdateQuestion(USER_ID, questionItem, AnswerItems, DataQuestionToUpDate))
                {
                    ClearData();
                    this.SuccessNotify("Update question finished");
                }
                else
                {
                    this.ErrorNotify("Update question failed");
                }
            }
            else
            {
                this.ErrorNotify("Please enter your answers");
            }

            SetState(ACTION_STATE.Insert);
            LoadQuestionListData();
        }

        private void UpdateGUI()
        {
            if (DataQuestionToUpDate != null && DataQuestionToUpDate.Count > 0)
            {
                QUESTION _question = DataQuestionToUpDate["QUESTION"] as QUESTION;
                List<QUESTION_INFO> _question_info = DataQuestionToUpDate["List_QUESTION_INFO"] as List<QUESTION_INFO>;
                if (_question != null && _question_info != null)
                {
                    foreach (QUESTION_INFO itemInfo in _question_info)
                    {
                        switch (itemInfo.QUESTION_INFO_PROP.Trim())
                        {
                            case "COURSE" :
                                string coureID = itemInfo.QUESTION_INFO_VALUE;
                                for (int i = 0; i < Courses.Count; i++)
                                {
                                    var item = Courses[i];
                                    if (item.ID.ToString().Equals(coureID))
                                    {
                                        cbCourse.SelectedIndex = i;
                                        break;
                                    }
                                }
                                break;
                            case "TIME":
                                string time = itemInfo.QUESTION_INFO_VALUE;
                                if (time.Equals("1"))
                                {
                                    cbTime.SelectedIndex = 0;
                                }
                                else if (time.Equals("2"))
                                {
                                    cbTime.SelectedIndex = 1;
                                }
                                else
                                {
                                    cbTime.SelectedIndex = 2;
                                }
                                break;
                            case "PROFESSOR_NAME":
                                string name = itemInfo.QUESTION_INFO_VALUE;
                                cbProfessor.Text = name;
                                break;
                            case "PROFESSOR_ID":
                                //problem???
                                break;
                        }
                    }

                    _question.USER_ID = USER_ID;
                    _question.QUESTION_TYPE = "SINGLE_RESPONSE";
                    rtbQuestionContent.Text = _question.QUESTION_DESCRIPTION;
                    if (_question.QUESTION_LEVEL.Equals("1"))
                    {
                        cbDiffculty.SelectedIndex = 0;
                    } else if (_question.QUESTION_LEVEL.Equals("2"))
                    {
                        cbDiffculty.SelectedIndex = 1;
                    } else 
                    {
                        cbDiffculty.SelectedIndex = 2;
                    }

                    FIGURELINK _figureLink = DataQuestionToUpDate["FIGURELINK"] as FIGURELINK;
                    if (_figureLink != null && !String.IsNullOrEmpty(_figureLink.FIGURE_PATH.Trim()))
                    {
                        Image img = new Bitmap(_figureLink.FIGURE_PATH);
                        pbImageQuestion.Image = img;
                    }

                    

                    ////okie, get solusion of this question
                    List<QUESTION_ITEM> _question_item = DataQuestionToUpDate["List_QUESTION_ITEM"] as List<QUESTION_ITEM>;
                    List<QUESTION_ITEM_FIGURE> _question_item_figure = DataQuestionToUpDate["List_QUESTION_ITEM_FIGURE"] as List<QUESTION_ITEM_FIGURE>;
                    List<QUESTION_SOLUTION> _question_item_solusion = DataQuestionToUpDate["List_QUESTION_SOLUTION"] as List<QUESTION_SOLUTION>;
                    List<FIGURELINK> _question_item_figureLink = DataQuestionToUpDate["List_FIGURELINK"] as List<FIGURELINK>;

                    for (int i = 0; i < _question_item.Count; i++)
                    {
                        Dictionary<int, Control> answerPanel = AnswerItemArray[i];

                        RadioButton cbCorrect = answerPanel[RADIO_CHECK_CORRECT] as RadioButton;
                        RichTextBox rtbAnswerContent = answerPanel[RICHTEXTBOX_ANSWER_CONTENT] as RichTextBox;
                        PictureBox pbImageAnswer = answerPanel[PICTUREBOX_IMAGE] as PictureBox;
                        if (cbCorrect != null && rtbAnswerContent != null && pbImageAnswer != null)
                        {
                            rtbAnswerContent.Text = _question_item[i].ITEM_FACE;
                            cbCorrect.Checked = _question_item[i].ITEM_VALUE.Equals("True") ? true : false;
                            if (!String.IsNullOrEmpty(_question_item_figure[i].ITEM_FIGURE_DESC.Trim()))
                            {
                                Image img = new Bitmap(_question_item_figure[i].ITEM_FIGURE_DESC);
                                pbImageAnswer.Image = img;
                            }
                        }
                    }
                }
            }
        }

        private void btnCreateQuestion_Click(object sender, EventArgs e)
        {
            Diffculty _diffculty = Diffculties[cbDiffculty.SelectedIndex];
            Course _course = Courses[cbCourse.SelectedIndex];
            Time _time = Times[cbTime.SelectedIndex];
            Professor _professor = Professors[cbProfessor.SelectedIndex];
            string _imagePath = pbImageQuestion.Tag != null ? pbImageQuestion.Tag.ToString() : "";
            string _questionContent = rtbQuestionContent.Text;
            if (String.IsNullOrEmpty(_questionContent))
            {
                this.ErrorNotify("Please enter your question.");
                return;
            }

            QuestionItem questionItem = new QuestionItem();
            questionItem.Diffculty = _diffculty;
            questionItem.Course = _course;
            questionItem.Time = _time;
            questionItem.Professor = _professor;
            questionItem.ImagePath = _imagePath;
            questionItem.QuestionContent = _questionContent;

            List<AnswerItem> AnswerItems = new List<AnswerItem>();

            foreach (Dictionary<int, Control> answerPanel in AnswerItemArray)
            {
                if (answerPanel != null && answerPanel.ContainsKey(RADIO_CHECK_CORRECT)
                                        && answerPanel.ContainsKey(RICHTEXTBOX_ANSWER_CONTENT)
                                        && answerPanel.ContainsKey(PICTUREBOX_IMAGE))
                {
                    RadioButton cbCorrect = answerPanel[RADIO_CHECK_CORRECT] as RadioButton;
                    RichTextBox rtbAnswerContent = answerPanel[RICHTEXTBOX_ANSWER_CONTENT] as RichTextBox;
                    PictureBox pbImageAnswer = answerPanel[PICTUREBOX_IMAGE] as PictureBox;

                    if (cbCorrect != null && rtbAnswerContent != null && pbImageAnswer != null)
                    {
                        AnswerItem item = new AnswerItem();
                        string _answerContent = rtbAnswerContent.Text.Trim();
                        if (String.IsNullOrEmpty(_answerContent))
                        {
                            //ignore empty question
                            continue;
                        }
                        item.TextContent = _answerContent;
                        item.Correct = cbCorrect.Checked;
                        item.ImagePath = pbImageAnswer.Tag != null ? pbImageAnswer.Tag.ToString() : "";

                        AnswerItems.Add(item);
                    }
                }
            }

            if (AnswerItems.Count > 0)
            {
                if (PushBussiness.getInstace().PushQuestion(USER_ID, questionItem, AnswerItems))
                {
                    ClearData();
                    this.SuccessNotify("Create question finished");
                }
                else
                {
                    this.ErrorNotify("Create question failed");
                }
            }
            else
            {
                this.ErrorNotify("Please enter your answers");
            }

            SetState(ACTION_STATE.Insert);
            LoadQuestionListData();
        }

        private void ClearData()
        {
            pbImageQuestion.Image = global::TestingSystem.Properties.Resources.defaul_image;
            pbImageQuestion.Tag = null;
            rtbQuestionContent.Text = "";
            foreach (Dictionary<int, Control> answerPanel in AnswerItemArray)
            {
                if (answerPanel != null && answerPanel.ContainsKey(RADIO_CHECK_CORRECT)
                                        && answerPanel.ContainsKey(RICHTEXTBOX_ANSWER_CONTENT)
                                        && answerPanel.ContainsKey(PICTUREBOX_IMAGE))
                {
                    RadioButton cbCorrect = answerPanel[RADIO_CHECK_CORRECT] as RadioButton;
                    RichTextBox rtbAnswerContent = answerPanel[RICHTEXTBOX_ANSWER_CONTENT] as RichTextBox;
                    PictureBox pbImageAnswer = answerPanel[PICTUREBOX_IMAGE] as PictureBox;

                    rtbAnswerContent.Text = "";
                    pbImageAnswer.Image = global::TestingSystem.Properties.Resources.defaul_image;
                    pbImageAnswer.Tag = null;
                }
            }
        }

        void ErrorNotify(string errorMessage)
        {
            if (!String.IsNullOrEmpty(errorMessage))
            {
                MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void SuccessNotify(string doneMessage)
        {
            if (!String.IsNullOrEmpty(doneMessage))
            {
                MessageBox.Show(doneMessage, "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (table != null)
            {
                DataGridViewSelectedRowCollection rowSelected = dataGridViewQuestion.SelectedRows;

                foreach (DataGridViewRow item in rowSelected)
                {
                    DataGridViewCell cell = item.Cells[0];
                    decimal question_id = (decimal)cell.Value;

                    //delete 
                    QUESTION _question = new QUESTION();
                    _question.QUESTION_ID = (int)question_id;

                    DAO_Question.Delete(_question);
                }

                LoadQuestionListData();
            }
        }
        
        private void btrUpdate_Click(object sender, EventArgs e)
        {
            if (table != null)
            {
                DataQuestionToUpDate.Clear();

                DataGridViewSelectedRowCollection rowSelected = dataGridViewQuestion.SelectedRows;

                foreach (DataGridViewRow item in rowSelected)
                {
                    DataGridViewCell cell = item.Cells[0];
                    decimal question_id = (decimal)cell.Value;

                    QUESTION _question = DAO_Question.Select((int)question_id);
                    DataQuestionToUpDate.Add("QUESTION", _question);

                    QUESTION_FIGURE _questionFigure = DAO_Question_Figure.Select((int)question_id);
                    DataQuestionToUpDate.Add("QUESTION_FIGURE", _questionFigure);

                    FIGURELINK _figureLink = DAO_FigureLink.Select((int)_questionFigure.FIGURE_ID);
                    DataQuestionToUpDate.Add("FIGURELINK", _figureLink);

                    List<QUESTION_INFO> _question_info = DAO_Question_Info.Select((int)question_id);
                    DataQuestionToUpDate.Add("List_QUESTION_INFO", _question_info);

                    //okie, get solusion of this question
                    List<QUESTION_ITEM> _question_item = DAO_Question_Item.Select((int)question_id);
                    DataQuestionToUpDate.Add("List_QUESTION_ITEM", _question_item);

                    List<QUESTION_ITEM_FIGURE> _question_item_figure = new List<QUESTION_ITEM_FIGURE>();
                    DataQuestionToUpDate.Add("List_QUESTION_ITEM_FIGURE", _question_item_figure);

                    List<QUESTION_SOLUTION> _question_item_solusion = new List<QUESTION_SOLUTION>();
                    DataQuestionToUpDate.Add("List_QUESTION_SOLUTION", _question_item_solusion);

                    List<FIGURELINK> _question_item_figureLink = new List<FIGURELINK>();
                    DataQuestionToUpDate.Add("List_FIGURELINK", _question_item_figureLink);

                    if (_question_item != null)
                    {
                        foreach (var questionItem in _question_item)
                        {
                            QUESTION_ITEM_FIGURE figure = DAO_Question_Item_Figure.Select((int)questionItem.ITEM_ID);
                            _question_item_figure.Add(figure);

                            QUESTION_SOLUTION solution = DAO_Question_Solution.Select((int)questionItem.ITEM_ID);
                            _question_item_solusion.Add(solution);

                            FIGURELINK _figureLinkTemp = DAO_FigureLink.Select((int)figure.FIGURE_ID);
                            _question_item_figureLink.Add(_figureLinkTemp);
                        }
                    }
                }

                SetState(ACTION_STATE.Update);
                UpdateGUI();
            }
        }

        private void btnCancelUpdate_Click(object sender, EventArgs e)
        {
            SetState(ACTION_STATE.Insert);
            ClearData();
        }

        private void rtbQuestionContent_TextChanged(object sender, EventArgs e)
        {

        }

        private void rtbAnswerContent_2_TextChanged(object sender, EventArgs e)
        {

        }

    }
}
